package com.zyx.javademo.nio.channel;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author Yaxi.Zhang
 * @since 2021/9/17 13:24
 * desc: FileChannel从buffer中读取数据
 */
public class FileChannelWrite {
    public static void main(String[] args) {
        // 创建FileChannel
        try (RandomAccessFile raf = new RandomAccessFile("input/nio/write01.txt", "rw");
             FileChannel channel = raf.getChannel()) {
            // 创建buffer
            ByteBuffer buf = ByteBuffer.allocate(1024);
            // buffer中写入数据
            buf.put("Read string to buffer".getBytes());
            // 将buffer中的数据写入channel中
            buf.flip();
            while (buf.hasRemaining()) {
                channel.write(buf);
            }

            System.out.println("写入成功");

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
